/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.kramerius.articles.importFromLn.reindexing;

import cz.mzk.kramerius.commons.Dom4jUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Node;
import org.dom4j.XPath;

/**
 *
 * @author Martin Řehánek (rehan at mzk.cz)
 */
public class IssueUuidCollector {

    private static final Logger logger = Logger.getLogger(IssueUuidCollector.class.getName());
    private static final String LOG_FILE_SUFFIX = ".xml";
    private static final String UUID_PREFIX = "uuid:";
    private static final XPath issuePidPath = DocumentHelper.createXPath("/article/issue/@PID");
    public Set<String> uuids = new HashSet<String>();
    private FilenameFilter logFilter = new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.endsWith(LOG_FILE_SUFFIX);
        }
    };

    /**
     *
     * @param dirList list of directories containing import logs
     */
    public IssueUuidCollector(List<File> dirList) {
        for (File logDir : dirList) {
            logger.log(Level.INFO, "processing dir {0}", logDir.getAbsolutePath());
            processLogDir(logDir);
        }
    }

    /**
     *
     * @return set of uuid of all issues that appear in import logs
     */
    public Set<String> getIssueUuids() {
        return uuids;
    }

    private void processLogDir(File logDir) {
        File[] logFiles = logDir.listFiles(logFilter);
        for (File logFile : logFiles) {
            List<String> issuesUuids = findIssues(logFile);
            uuids.addAll(issuesUuids);
        }
    }

    private List<String> findIssues(File logFile) {
        try {
            Document doc = Dom4jUtils.loadDocument(logFile, false);
            List<Node> nodes = issuePidPath.selectNodes(doc);
            List<String> result = new ArrayList<String>(nodes.size());
            for (Node node : nodes) {
                String pid = node.getText();
                String uuid = pid.substring(UUID_PREFIX.length());
                result.add(uuid);
            }
            return result;
        } catch (FileNotFoundException ex) {
            Logger.getLogger(IssueUuidCollector.class.getName()).log(Level.SEVERE, null, ex);
            return Collections.<String>emptyList();
        } catch (DocumentException ex) {
            Logger.getLogger(IssueUuidCollector.class.getName()).log(Level.SEVERE, null, ex);
            return Collections.<String>emptyList();
        }
    }
}
